/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network.tcp;

import java.io.IOException;
import java.util.TimerTask;

public class TCPAcceptorConnection extends TCPConnection {
	private static final long DEFAULT_HANDSHAKE_TIMEOUT = 30; // 10 second 
	
	private TCPAcceptor acceptor;
	protected class HandshakeTimeoutHandler extends TimerTask {

		@Override
		public void run() {
			if(TCPAcceptorConnection.this.handshakeManager!=null && !TCPAcceptorConnection.this.handshakeManager.isHandshaked()) {
				destroy();
			}
		}
		
	}
	HandshakeTimeoutHandler handshakeTimeoutHandler = null;
	
	public TCPAcceptorConnection(TCPSharedResources resources, TCPAcceptor acceptor) throws IOException {
		super(resources);
		this.acceptor = acceptor;
		if(this.handshakeManager!=null) {
			handshakeTimeoutHandler = new HandshakeTimeoutHandler();
			this.resources.getHandshakeTimer().schedule( handshakeTimeoutHandler, DEFAULT_HANDSHAKE_TIMEOUT * 1000);
		}
	}
	
	
	@Override
	protected void fireOnConnected() {
		channelLock.lock();
		try {
			if(this.acceptor!=null) {
				this.acceptor.fireOnAccepted(this);
			}
		}
		finally {
			channelLock.unlock();
		}			
	}
		
	@Override
	public void close() {
		channelLock.lock();
		try {
			if(this.acceptor!=null) {
				this.acceptor.removeConnection ( this );
				this.acceptor = null;
			}
			super.close();
		}
		finally {
			channelLock.unlock();
		}
	}


	@Override
	public boolean isAcceptorConnection() {
		return true;
	}
		
}
